package xin.marcher.module.trace.mp.consumer.listener;

import com.fasterxml.jackson.core.type.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import xin.marcher.module.common.domain.TraceData;
import xin.marcher.module.common.utils.JsonUtil;
import xin.marcher.module.trace.repository.TraceDataRepository;

import java.util.List;

/**
 * 把商品溯源信息保存到es
 */
@Slf4j
@Component
public class ProductTraceListener implements MessageListenerConcurrently {

    @Autowired
    private TraceDataRepository traceDataRepository;

    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        try {
            for (MessageExt messageExt : list) {
                String msg = new String(messageExt.getBody());
                log.info("把商品溯源信息保存到es，消息内容：{}", msg);

                List<TraceData> traceDataList = JsonUtil.json2Object(msg, new TypeReference<List<TraceData>>() {
                });
                if (!CollectionUtils.isEmpty(traceDataList)) {
                    traceDataRepository.saveTraceDataList(traceDataList);
                }
            }
        } catch (Exception e) {
            log.error("consume error, 把商品溯源信息保存到es失败", e);
            // 本次消费失败，下次重新消费
            return ConsumeConcurrentlyStatus.RECONSUME_LATER;
        }
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
